--#include "data\config\activityconfig\CrossActivity\CrossGatherCrystalCfg.lua" once
--#include "data\functions\Common\RankMgr.lua" once 		--排行榜管理

--开始
function CrossGatherCrystalStart()
	gRankMgr_Clear(RANK_CROSS_GATHER_CRYSTAL)

	local sysVar = System.getDyanmicVar()
	sysVar.crossGatherCrystalAwardFlag = nil
	sysVar.crossGatherCrystalStartFlag = 1

	if Lang.ScriptTips.CrossGatherCrystalTip001 ~= "" then
		System.broadcastTipmsg(Lang.ScriptTips.CrossGatherCrystalTip001,ttScreenCenter + ttChatWindow)
	end
end

--活动判断
function IsCrossGatherCrystal(sysarg)
	local mySceneId =  Actor.getSceneId(sysarg)
	if(mySceneId == CrossGatherCrystalCfg.sceneId)then
		return true
	end
	return false
end

--结束
function CrossGatherCrystalEnd()
	local sysVar = System.getDyanmicVar()
	sysVar.crossGatherCrystalAwardFlag = 1
	sysVar.crossGatherCrystalStartFlag = nil

	if Lang.ScriptTips.CrossGatherCrystalTip002 ~= "" then
		System.broadcastTipmsg(Lang.ScriptTips.CrossGatherCrystalTip002,ttScreenCenter + ttChatWindow)
	end

	local playerList = LuaHelp.getSceneActorListById(CrossGatherCrystalCfg.sceneId)  --获取在线玩家对象列表	
	if(playerList == nil)then
		return
	end
	for k,v in pairs(playerList)do	--踢出场景
		CrossGatherCrystalUpdate(v)
		CrossGatherCrystalLeaveActivityHandler(v)
		SendActivityLog(v, ACTIVITY_DEFINE_CROSS_CRYSTAL, ActLogStatus_Complete)
	end
end

--水晶生成
function CrossGatherCrystalMob(value)
	local index = tonumber(value)
	local config = CrossGatherCrystalCfg.Crystals[index]
	if not config then
		return
	end
	local needBroadCastNumTable = {}
	if config.broadcastMonsterIds then
		local len = #config.broadcastMonsterIds
		if len > 0 then
			for idx = 1, len do
				needBroadCastNumTable[config.broadcastMonsterIds[idx]] = 0
			end
		end
	end
	if config.monsters then
		local len = #config.monsters
		if len > 0 then
			for idx = 1, len do
				local cfg = config.monsters[idx]
				if needBroadCastNumTable[cfg.monsterId] then
					needBroadCastNumTable[cfg.monsterId] = needBroadCastNumTable[cfg.monsterId] + cfg.num
				end
				if cfg.pos then
					freshSceneMonsterInPosForce(cfg)
				end
				if cfg.range then
					freshSceneMonsterInRangeForce(cfg)
				end
			end
		end
	end
	if config.msg and config.broadcastMonsterIds then
		local len = #config.broadcastMonsterIds
		if len > 0 then
			for idx = 1, len do
				local number = needBroadCastNumTable[config.broadcastMonsterIds[idx]]
				if needBroadCastNumTable[config.broadcastMonsterIds[idx]] > 0 then
					local monName = MonsterNameDeleteNumber(config.broadcastMonsterIds[idx])
					local msgStr = string.format(config.msg, monName, number)
					System.broadcastTipmsg(msgStr,ttScreenCenter + ttChatWindow)
				end
			end
		end
		
	end
end

--活动是否开始
function IsCrossGatherCrystalStart()
	local sysVar = System.getDyanmicVar()
	if sysVar.crossGatherCrystalStartFlag then
		return true
	end
	return false
end

--奖励是否可以领取
function IsCrossGatherCrystalCanGetAward()
	local sysVar = System.getDyanmicVar()
	if sysVar.crossGatherCrystalAwardFlag then
		return true
	end
	return false
end

--失去物品
function CrossGatherCrystalDropItem( sysarg, itemId, itemCount )
    if not IsCrossGatherCrystalStart() then
        return 
    end

    if not IsCrossGatherCrystal(sysarg) then
        return
    end
    if itemCount > 0 then
		for idx = 1, #CrossGatherCrystalCfg.ExchangeItems do
	   		local cfg = CrossGatherCrystalCfg.ExchangeItems[idx]
	   		local num = Actor.getItemCount(sysarg, cfg.id)
	   		if num > 0 then
	   			return
	   		end
	   	end
        SetPropertyHeadItemValue(sysarg, 4, 0)  --删除头部item
    end
end

--获得物品
function CrossGatherCrystalPickItem( sysarg, itemId, itemCount )
    if IsCrossGatherCrystal(sysarg) and IsCrossGatherCrystalStart() then
        if itemCount > 0 then
            SetPropertyHeadItemValue(sysarg, 4, CrossGatherCrystalCfg.ShowTitleItemId)  --增加头部item
        end
    end
end

--上交水晶
function CrossGatherCrystalExchange(sysarg)
	----[[
	if not Actor.IsCross(sysarg) then
		return
	end
	--]]
	if not IsCrossGatherCrystalStart() then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossGatherCrystalTip007, ttFlyTip)
        return 
    end

    if not IsCrossGatherCrystal(sysarg) then
        return
    end

   	local AddScore = 0
   	for idx = 1, #CrossGatherCrystalCfg.ExchangeItems do
   		local cfg = CrossGatherCrystalCfg.ExchangeItems[idx]
   		local num = Actor.getItemCount(sysarg, cfg.id)
   		if num > 0 then
   			if not DoConsumeCond( sysarg, cfg.consume, num, LogIds.CrossGatherCrystalLogId, Lang.LogTips.CrossGatherCrystal ) then
            	return 
        	end
        	AddScore = AddScore + num * cfg.score
   		end
   	end

   	if AddScore == 0 then
   		Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossGatherCrystalTip003, ttFlyTip)
		return
	end

   	local nActorId = Actor.getIntProperty( sysarg, PROP_ENTITY_ID ) 

	local myBeforeIdx = 0
	local rankName = RankList[RANK_CROSS_GATHER_CRYSTAL].strName
	local rankingPtr = Ranking.getRanking( rankName )
	if rankingPtr then
		local item = Ranking.getItemPtrFromId( rankingPtr, nActorId)
		if item then
			local myScore = Ranking.getPoint(item) or 0
			if myScore < CrossGatherCrystalCfg.rankLimit then			--未上榜
				myBeforeIdx = 0
			else
				myBeforeIdx = Ranking.getIndexFromPtr(item) + 1
				if myBeforeIdx >= CrossGatherCrystalCfg.rankAwards[#CrossGatherCrystalCfg.rankAwards].cond[1] then
					myBeforeIdx = 0
				end
			end
		end	
	end

	--增加个人榜积分
	gRankMgr_AddValue(nActorId, RANK_CROSS_GATHER_CRYSTAL, AddScore)

	local myCurIdx = 0
	if rankingPtr then
		local item = Ranking.getItemPtrFromId( rankingPtr, nActorId)
		if item then
			local myScore = Ranking.getPoint(item) or 0
			if myScore < CrossGatherCrystalCfg.rankLimit then			--未上榜
				myCurIdx = 0
			else
				myCurIdx = Ranking.getIndexFromPtr(item) + 1
				if myCurIdx >= CrossGatherCrystalCfg.rankAwards[#CrossGatherCrystalCfg.rankAwards].cond[1] then
					myCurIdx = 0
				end
			end
		end	
	end

	Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.CrossGatherCrystalTip004,AddScore), ttTipmsgWindow)


	if myCurIdx == 1 or myCurIdx ~= myBeforeIdx then
		CrossGatherCrystalGetRank(sysarg)
	else
		CrossGatherCrystalUpdate(sysarg)
	end
end

--领取奖励
function CrossGatherCrystalGetAward(sysarg, packet)
	----[[
	if not Actor.IsCross(sysarg) then
		return
	end
	--]]
	if not IsCrossGatherCrystalCanGetAward() then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossGatherCrystalTip005, ttFlyTip)
		return
	end

	local rankName = RankList[RANK_CROSS_GATHER_CRYSTAL].strName
	local rankingPtr = Ranking.getRanking( rankName )
	if (rankingPtr == nil) then
		return
	end

   	local rankLimit = CrossGatherCrystalCfg.rankLimit
   	local awardLimit = CrossGatherCrystalCfg.rewardLimit
	local myId = Actor.getActorId(sysarg)
	local myScore 	= 0
	local myIdx 	= 0
	local myState   = 0
	local myAwardConfig
	local item = Ranking.getItemPtrFromId( rankingPtr, myId)
	if item then
		myScore = Ranking.getPoint(item) or 0
		myState = tonumber(Ranking.getSub(item, 1)) or 0
		if myScore >= rankLimit then			--未上榜
			myIdx = Ranking.getIndexFromPtr(item) + 1
			if myIdx >= CrossGatherCrystalCfg.rankAwards[#CrossGatherCrystalCfg.rankAwards].cond[1] then
				myIdx = 0
				myAwardConfig = CrossGatherCrystalCfg.rankAwards[#CrossGatherCrystalCfg.rankAwards]	
			else
				myAwardConfig = GetElemByCond( CrossGatherCrystalCfg.rankAwards, myIdx )
			end
		elseif myScore >= awardLimit then
			myIdx = 0
			myAwardConfig = CrossGatherCrystalCfg.rankAwards[#CrossGatherCrystalCfg.rankAwards]
		else
			myIdx = 0
		end

		if not myAwardConfig then
			Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossGatherCrystalTip005, ttFlyTip)
			return
		end
		if myState == 2 then
			Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossGatherCrystalTip006, ttFlyTip)
			return
		end
		if myAwardConfig.awards then
			if IsBagGridEnough(sysarg, myAwardConfig.awards) then
				myState = 2
				Ranking.setSub(item, 1, myState)
				GiveCommonAward(sysarg, myAwardConfig.awards, LogIds.CrossGatherCrystalLogId, Lang.LogTips.CrossGatherCrystal)

				CrossGatherCrystalUpdate(sysarg)
			else	
				Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0015, ttFlyTip)
			end
		end
	end
end

--怪物死亡
function CrossGatherCrystalMonDie(monster, sysarg, monId)
	local IsRefresh = false
	for idx = 1, #CrossGatherCrystalCfg.RandomMonsterId do
		if monId == CrossGatherCrystalCfg.RandomMonsterId[idx] then
			IsRefresh = true
			break
		end
	end
	if IsRefresh then
		local hScene = Fuben.getSceneHandleById(CrossGatherCrystalCfg.sceneId,0)
		if  hScene == 0 then
		    return
		end
		local ii, event = GetItemIdxRand(CrossGatherCrystalCfg.RandomEvent)
		if event and event.monsters then
			for idx, monsterCfg in pairs( event.monsters ) do
				local x, y = Actor.getEntityPosition(monster, 0, 0)
				local x1 = x - monsterCfg.range[1]
				local y1 = y - monsterCfg.range[2]
				local x2 = x + monsterCfg.range[3]
				local y2 = y + monsterCfg.range[4]
				Fuben.createMonstersInRange(hScene,monsterCfg.monsterId, x1,y1,x2,y2,monsterCfg.num, monsterCfg.livetime)

				if event.msg and event.msg ~= "" then
					local actorName = Actor.getName(sysarg)
					local monsterName = MonsterNameDeleteNumber(monsterCfg.monsterId)
					local strMsg = string.format(event.msg, actorName, monsterName)
					System.broadcastTipmsg(strMsg,ttScreenCenter + ttChatWindow)
				end
			end
		end
	end
end

--前端请求获得排行榜
function CrossGatherCrystalGetRank(sysarg)
	----[[
	if not Actor.IsCross(sysarg) then
		return
	end
	--]]
	local rankName = RankList[RANK_CROSS_GATHER_CRYSTAL].strName
	local rankingPtr = Ranking.getRanking( rankName )
	if (rankingPtr == nil) then
		return
	end
	local num = CrossGatherCrystalCfg.RankShowNum
	local itemNum = Ranking.getRankItemCountByLimit(rankingPtr, CrossGatherCrystalCfg.rankLimit)
	if num < itemNum then
		itemNum = num
	end
	local pack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sCrossGatherCrystalData)
	if (pack == nil) then
		return
	end
	--我的数据
	local myId = Actor.getActorId(sysarg)
	local myScore 	= 0
	local myIdx 	= 0
	local myAwardState = 0
	local needChangeAwardState = false
	local item = Ranking.getItemPtrFromId( rankingPtr, myId)
	if item then
		myScore = Ranking.getPoint(item) or 0
		if myScore >= CrossGatherCrystalCfg.rankLimit then			
			myIdx = Ranking.getIndexFromPtr(item) + 1
			if myIdx >= CrossGatherCrystalCfg.rankAwards[#CrossGatherCrystalCfg.rankAwards].cond[1] then
				myIdx = 0
			end
			myAwardState = tonumber(Ranking.getSub(item, 1))
			needChangeAwardState = true
		elseif myScore >= CrossGatherCrystalCfg.rewardLimit then
			myAwardState = tonumber(Ranking.getSub(item, 1))
			myIdx = 0
			needChangeAwardState = true
		else
			myIdx = 0
		end
	end	
	if not myAwardState then
		myAwardState = 0
	end
	if needChangeAwardState and IsCrossGatherCrystalCanGetAward() and myAwardState == 0 then
		myAwardState = 1
	end

	DataPack.writeShort(pack, myIdx)
	--print("myIdx="..myIdx)
	DataPack.writeInt(pack, myScore)
	--print("myScore="..myScore)
	DataPack.writeByte(pack, myAwardState)
	--print("myAwardState="..myAwardState)

	if itemNum > 0 then
		local pos = DataPack.getDataPackPos(pack)
		local nCount = 0
		DataPack.writeByte(pack, nCount)
		for idx=1, itemNum do
			--print("idx="..idx)
			local rankItem = Ranking.getItemFromIndex(rankingPtr, idx-1)
			if rankItem then
				local value = Ranking.getPoint(rankItem)
				local name = Ranking.getSub(rankItem, 0)
				DataPack.writeString(pack, name)
				--print("name="..name)	
				--print("name = "..name)		
				DataPack.writeInt(pack, value)
				--print("value="..value)
				--print("value = "..value)
				nCount = nCount + 1
			end
		end
		DataPack.writeByteByPtr(pack, pos, nCount)
	else
		DataPack.writeByte(pack, 0)
	end

	DataPack.flush(pack)
end

--数据更新
function CrossGatherCrystalUpdate(sysarg)
	----[[
	if not Actor.IsCross(sysarg) then
		return
	end
	--]]
	local pack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sCrossGatherCrystalState)
	if (pack == nil) then
		return
	end
	local rankName = RankList[RANK_CROSS_GATHER_CRYSTAL].strName
	local rankingPtr = Ranking.getRanking( rankName )
	if (rankingPtr == nil) then
		return
	end
	--我的数据
	local myId = Actor.getActorId(sysarg)
	local myScore 	= 0
	local myIdx 	= 0
	local myAwardState = 0
	local needChangeAwardState = false
	local item = Ranking.getItemPtrFromId( rankingPtr, myId)
	if item then
		myScore = Ranking.getPoint(item) or 0
		if myScore >= CrossGatherCrystalCfg.rankLimit then			
			myIdx = Ranking.getIndexFromPtr(item) + 1
			if myIdx >= CrossGatherCrystalCfg.rankAwards[#CrossGatherCrystalCfg.rankAwards].cond[1] then
				myIdx = 0
			end
			myAwardState = tonumber(Ranking.getSub(item, 1))
			needChangeAwardState = true
		elseif myScore >= CrossGatherCrystalCfg.rewardLimit then
			myAwardState = tonumber(Ranking.getSub(item, 1))
			myIdx = 0
			needChangeAwardState = true
		else
			myIdx = 0
		end
	end	
	if not myAwardState then
		myAwardState = 0
	end
	if needChangeAwardState and IsCrossGatherCrystalCanGetAward() and myAwardState == 0 then
		myAwardState = 1
	end

	DataPack.writeShort(pack, myIdx)
	--print("myIdx="..myIdx)
	DataPack.writeInt(pack, myScore)
	--print("myScore="..myScore)
	DataPack.writeByte(pack, myAwardState)
	--print("myAwardState="..myAwardState)
	
	DataPack.flush(pack)
end

--离开场景
function CrossGatherCrystalLeaveActivityHandler(sysarg)
	if IsCrossGatherCrystal(sysarg) and IsCrossGatherCrystalStart() then
		for idx = 1, #CrossGatherCrystalCfg.ExchangeItems do
	   		local cfg = CrossGatherCrystalCfg.ExchangeItems[idx]
	   		local num = Actor.getItemCount(sysarg, cfg.id)
	   		if num > 0 then
	   			SetPropertyHeadItemValue(sysarg, 4, 0)
	   			return
	   		end
	   	end
	end
end

--进入场景
function CrossGatherCrystalEnterActivityHandler(sysarg)
    if IsCrossGatherCrystal(sysarg) and IsCrossGatherCrystalStart() then
        for idx = 1, #CrossGatherCrystalCfg.ExchangeItems do
	   		local cfg = CrossGatherCrystalCfg.ExchangeItems[idx]
	   		local num = Actor.getItemCount(sysarg, cfg.id)
	   		if num > 0 then
	   			SetPropertyHeadItemValue(sysarg, 4, CrossGatherCrystalCfg.ShowTitleItemId)
	   			return
	   		end
	   	end
    end
end

--gm
function GmCrossGatherCrystal(sysarg, param1, param2)
	if param1 == 1 then
		if param2 == 1 then
			CrossGatherCrystalStart()
		elseif param2 == 2 then
			CrossGatherCrystalEnd()
		elseif param2 == 3 then
			CrossGatherCrystalGetRank(sysarg)
		elseif param2 == 4 then
			CrossGatherCrystalExchange(sysarg)
		elseif param2 == 5 then
			CrossGatherCrystalGetAward(sysarg)
		elseif param2 == 6 then
			CrossGatherCrystalUpdate(sysarg)
		end
	elseif param1 == 2 then
		CrossGatherCrystalMob(param2)
	end
end

